const generateBrowser = require('./generateBrowser')

/**
 * web page 导出PDF
 * @param { String } url
 * @returns { Blob }
 */
async function exportWebPageToPDF ({ url }) {
  try {
    const page = await generateBrowser()
    await page.goto(url, { waitUntil: 'networkidle2' })
    await page.addStyleTag({ content: 'pre, blockquote, div, table { page-break-inside: avoid }' })
    const pdfBuffer = await page.pdf({
      format: 'A4',
      timeout: 30000,
      preferCSSPageSize: true,
      printBackground: true,
      '-webkit-print-color-adjust': 'exact',
      margin: {
        top: '1.5cm',
        right: '1.5cm',
        bottom: '1.5cm',
        left: '1.5cm'
      },
      displayHeaderFooter: false
    })
    page.close()
    return pdfBuffer
  } catch (error) {
    throw new Error(error)
  }
}

/**
 * web page导出JPG
 * @param {*} url
 * @returns { Blob }
 */
async function exportWebPageToJPG ({ url }) {
  try {
    const page = await generateBrowser()
    await page.goto(url, { waitUntil: 'networkidle2' })
    const imageBuffer = await page.screenshot({
      type: 'jpeg',
      quality: 100,
      fullPage: true
    })
    page.close()
    return imageBuffer
  } catch (error) {
    throw new Error(error)
  }
}

/**
 *
 * @param { String } md
 * @returns { Blob }
 */
async function exportWebArticleToMd ({ md }) {
  try {
    const mdBuffer = Buffer.from(md)
    return mdBuffer
  } catch (error) {
    throw new Error(error)
  }
}

module.exports = {
  exportWebPageToPDF,
  exportWebPageToJPG,
  exportWebArticleToMd
}
